package com.atguigu.springcloud.大批量任务处理.service;

import com.atguigu.springcloud.大批量任务处理.util.TaskBatchSendUtil;
import jakarta.annotation.Resource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author XiongJianLin
 * @date Created in 2025/2/10 16:31
 */
@Service
public class UserServiceImpl implements UserService{
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    @Override
    public List<String> getUserInfos(String userId) {
        Map<String,String> userInfo = new HashMap<>();
        userInfo.put("id","0001");

        long start = System.currentTimeMillis();
        CompletableFuture<Void> nameFuture = CompletableFuture.runAsync(() -> {
            userInfo.put("name",getName());
        }, taskExecutor);
        CompletableFuture<Void> fansNumFuture = CompletableFuture.runAsync(() -> {
            userInfo.put("fansNum",getFansNum());
        }, taskExecutor);

        CompletableFuture.allOf(nameFuture,fansNumFuture).join();

        long end = System.currentTimeMillis();
        System.out.println("获取用户信息耗时：" + (end - start) + "ms");
        ArrayList<String> strings = new ArrayList<>(userInfo.values());
        System.out.println(strings);
        return strings;
    }


    /**
     * 模拟微服务调用
     */
    public String getName(){
        try {
            TimeUnit.MICROSECONDS.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "dashuabi";
    }

    public String getFansNum(){
        try {
            TimeUnit.MICROSECONDS.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "666";
    }

    public String getMsgNum(){
        try {
            TimeUnit.MICROSECONDS.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        return "555";
    }
}
